package org.web.datajpa.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web.datajpa.constant.ResultEnum;
import org.web.datajpa.domain.Teacher;
import org.web.datajpa.exception.ResultException;
import org.web.datajpa.repository.TeacherRepository;

import java.util.List;

@Service
public class TeacherService {
    @Autowired
    private TeacherRepository teacherRepository;
    // 获取所有老师信息
    public List<Teacher> findAll() {
        return teacherRepository.findAll();
    }
    // 保存老师信息
    public Teacher add(Teacher teacher) {
        return teacherRepository.save(teacher);
    }
    // 根据id删除老师信息
    public void deleteById(Long id) {
        teacherRepository.deleteById(id);
    }
    // 根据id查找老师信息
    public Teacher findById(Long id) {
        return teacherRepository.findById(id).orElse(null);
    }
    // 修改老师信息
    public Teacher update(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

/*    // 根据教师编号前缀查找老师信息
    public List<Teacher> findTeacherWithMaxEmployeeId() { return teacherRepository.findTeachersWithMaxTeacherNumberPrefix();
    }*/
    // 根据姓名查找教师信息
    public List<Teacher> searchByName(String name) {return teacherRepository.findByNameContaining(name);
    }


    // 登录验证-验证工号和密码是否匹配
    public Teacher validateIdAndPwd(Long id, String password) throws Exception{
        Teacher teacher = teacherRepository.findById(id).orElse(null);
        if (teacher != null && teacher.getPassword().equals(password)) {
            //匹配
            return teacher;
        }else{
            throw new ResultException(ResultEnum.LOGIN_ERROR);
        }
    }

    // 分页查询
    public Page<Teacher> getAll(Pageable pageable){
        return teacherRepository.findAll(pageable);
    }
    // 分页查询
    public Page<Teacher> getAll(Example<Teacher> example, Pageable pageable){
        return teacherRepository.findAll(example,pageable);
    }


    // 根据id批量删除学生
    @Transactional
    public void deleteTeachersByIds(List<Integer> ids) {
        if (ids != null && !ids.isEmpty()) {
            teacherRepository.deleteByIds(ids);
        } else {
            throw new ResultException("工号ID列表不能为空");
        }
    }
}
